﻿using FineUICoreDesigner;
using FineUICoreDesigner.Base;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.IO;
using System.Linq;
using System.Text;

namespace FineUIDesignerVSIX.Handle
{
    public class RazorPagePartialHandle : IRazorPageAfterSave
    {
        public void Handle(RazorPageFileInfo editFileInfo)
        {
            if (!editFileInfo.IsPartial)
            {
                var cspath = editFileInfo.FileRootPath + "\\" + editFileInfo.CsFileName;
                var code = BaseHelp.GetCode(cspath);
                if (string.IsNullOrEmpty(code)) return;
                SyntaxTree tree = CSharpSyntaxTree.ParseText(code);
                CompilationUnitSyntax root = tree.GetCompilationUnitRoot();
                var firstClass = root.DescendantNodes()
                                .OfType<ClassDeclarationSyntax>()
                                .FirstOrDefault();
                if (firstClass != null && !firstClass.Modifiers.Any(m => m.IsKind(SyntaxKind.PartialKeyword)))
                {
                    // 如果这个类不是 Partial 类型，就将其改为 Partial 类型
                    ClassDeclarationSyntax newFirstClass = firstClass.AddModifiers(SyntaxFactory.Token(SyntaxKind.PartialKeyword));
                    root = root.ReplaceNode(firstClass, newFirstClass);
                    string newCode = root.NormalizeWhitespace().ToFullString();
                    BaseHelp.WriteAllText(cspath, newCode);
                    BaseHelp.OutputLine($"修改 {editFileInfo.CsFileName} 成功 🎉");
                }
            }
        }
    }
}
